package com.maximus.server.nio.singlethreadreactor;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SingleThreadReactor implements Runnable {
    private static final Logger logger = LogManager.getLogger(SingleThreadReactor.class);

    private ServerSocketChannel serverSocketChannel;

    private Selector selector;


    public SingleThreadReactor(int port) throws IOException {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(port));

        selector = Selector.open();

        //将通道注册到选择器上，监听accept事件，并且新建一个Acceptor对象作为附带对象
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT, new Acceptor(serverSocketChannel, selector));
    }

    @Override
    public void run() {
        while (true) {
            try {
                int select = selector.select();
                if (select > 0) {
                    Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                    Iterator<SelectionKey> keyIterator = selectionKeySet.iterator();
                    while (keyIterator.hasNext()) {
                        SelectionKey selectionKey = keyIterator.next();
                        dispatcher(selectionKey);
                        keyIterator.remove();
                    }
                }
            } catch (IOException e) {
                logger.error(e);
                throw new RuntimeException(e);
            }
        }
    }

    //分发事件
    private void dispatcher(SelectionKey selectionKey) {
        Runnable runnable = (Runnable) selectionKey.attachment();
        runnable.run();
    }


}
